<?php

namespace App\Http\Controllers\Admin;

use App\Models\ResourceBusinessName;
use App\Models\ResourceReadingList;
use App\Models\ResourceSystemType;
use App\Models\ResourceSystemTypeIntention;
use App\Models\ResourceTotal;
use App\Models\ResourceType;
use App\Models\ResourceTypeExternal;
use App\Validate\ResourceSystemTypeValidate;
use Illuminate\Support\Facades\DB;

/**
 * 数字资源总数据类型管理（系统类型，系统栏目）
 */
class ResourceSystemTypeController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->validate = new ResourceSystemTypeValidate();
        $this->model = new ResourceSystemType();
    }

    /**
     * 类型(用于下拉框选择)
     */
    public function filterList()
    {

        $condition[] = ['is_del', '=', 1];

        return $this->model->getFilterList(['id', 'type_name'], $condition, 'sort asc,id desc');
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param way string 书籍获取方式  1、筛选书籍  2、选择书单 3、选择书商  4、每日荐书  5 、自定义封面并选择书籍  (暂不支持修改)
     * @param location int 显示位置  null 查询所有  0 全部(自适应)  1 图书  2 有声 3 视频 4 期刊 5 报纸 99 首页
     * @param keywords string 搜索关键词(类型名称)
     * @param is_play string 是否发布  1 发布 2 不发布
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? $this->request->limit : 10;
        $res = $this->model->lists($this->request->all());
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $resourceTypeExternalModel = new ResourceTypeExternal();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['resource_business_name'] = !empty($val['resource_business_id']) ? ResourceBusinessName::getBusinessName($val['resource_business_id']) : '';
            $res['data'][$key]['reading_name'] = !empty($val['reading_id']) ? ResourceReadingList::getReadingListName($val['reading_id']) : '';
            $res['data'][$key]['resource_business_type_name'] = (!empty($val['resource_business_type_id']) && !empty($val['resource_business_id'])) ? $resourceTypeExternalModel->getBusinessTypeName($val['resource_business_id'], $val['resource_business_type_id']) : '';
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 类型id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $resourceTypeExternalModel = new ResourceTypeExternal();
        $res['resource_business_name'] = !empty($res['resource_business_id']) ? ResourceBusinessName::getBusinessName($res['resource_business_id']) : '';
        $res['reading_name'] = !empty($res['reading_id']) ? ResourceReadingList::getReadingListName($res['reading_id']) : '';
        $res['resource_business_type_name'] = (!empty($res['resource_business_type_id']) && !empty($res['resource_business_id'])) ? $resourceTypeExternalModel->getBusinessTypeName($res['resource_business_id'], $res['resource_business_type_id']) : '';

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param type_name string 类型名称
     * @param img string 图片
     * @param intro string 简介
     * @param way string 书籍获取方式  1、筛选书籍  2、选择书单 3、选择书商  4、每日荐书  5 、自定义封面并选择书籍  (暂不支持修改)
     * @param location int 显示位置  0 全部(内容自适应)  1 图书  2 有声 3 视频 4 期刊 5 报纸 99 首页
     * @param sort string 顺序
     * @param resource_business_id string 资源商id  多个逗号拼接
     * @param resource_business_type_id string 资源商下的类型id  多个逗号拼接
     * @param reading_id string 书单id
     * @param template string 模版，与设计图模版对应  书单，和自定义封面无模版（固定模版）   模版8 和 模版9，是与视频对应  模版8全视频 ，模版 9 视频和图片横排
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->way == 2 && empty($this->request->reading_id)) {
            return $this->returnApi(201, '书单不能为空');
        }
        if ($this->request->way == 4 && empty($this->request->read_id)) {
            return $this->returnApi(201, '每日推荐不能为空');
        }
        if (($this->request->way == 4 || $this->request->way == 5) && empty($this->request->img)) {
            return $this->returnApi(201, '封面不能为空');
        }
        if ($this->request->way == 3 && empty($this->request->resource_business_id)) {
            return $this->returnApi(201, '资源商ID不能为空');
        }
        if ($this->request->way != 3 && !empty($this->request->resource_business_type_id)) {
            return $this->returnApi(201, '资源商类型格式错误');
        }
        if (in_array($this->request->way, [1, 3]) && empty($this->request->template)) {
            return $this->returnApi(201, '模版不能为空');
        }
        // if (in_array($this->request->location, [1, 2, 3, 4, 5]) && !empty($this->request->resource_business_type_id) && $this->request->resource_business_type_id != $this->request->location) {
        //     return $this->returnApi(201, '显示位置与资源商的类型需要对应');
        // }
        $is_exists = $this->model->nameIsExists($this->request->type_name, 'type_name');
        if ($is_exists) {
            return $this->returnApi(202, "该名称已存在");
        }
        if (in_array($this->request->way, [2, 4, 5])) {
            $this->request->merge(['template' => '']);
        }
        if (empty($this->request->sort)) {
            $this->request->merge(['sort' => 0]);
        }
        $this->request->merge(['manage_id' => request()->manage_id]);
        $res = $this->model->add($this->request->all());

        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 修改
     * @param id int 类型id
     * @param type_name string 类型名称
     * @param img string 图片
     * @param intro string 简介
     * @param way string 书籍获取方式  1、筛选书籍  2、选择书单 3、选择书商  4、每日荐书  5 、自定义封面并选择书籍  (暂不支持修改)
     * @param location int 显示位置  0 全部(内容自适应)  1 图书  2 有声 3 视频 4 期刊 5 报纸 99 首页
     * @param sort string 顺序
     * @param resource_business_id string 资源商id  多个逗号拼接
     * @param resource_business_type_id string 资源商下的类型id  多个逗号拼接
     * @param reading_id string 书单id
     * @param read_id string 每日推荐id
     * @param template string 模版，与设计图模版对应  书单，和自定义封面无模版（固定模版）  模版8 和 模版9，是与视频对应  模版8全视频 ，模版 9 视频和图片横排
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if ($this->request->way == 2 && empty($this->request->reading_id)) {
            return $this->returnApi(201, '书单不能为空');
        }
        if ($this->request->way == 4 && empty($this->request->read_id)) {
            return $this->returnApi(201, '每日推荐不能为空');
        }
        if (($this->request->way == 4 || $this->request->way == 5) && empty($this->request->img)) {
            return $this->returnApi(201, '封面不能为空');
        }
        if ($this->request->way == 3 && empty($this->request->resource_business_id)) {
            return $this->returnApi(201, '资源商ID不能为空');
        }
        if ($this->request->way != 3 && !empty($this->request->resource_business_type_id)) {
            return $this->returnApi(201, '资源商类型格式错误');
        }
        if (in_array($this->request->way, [1, 3]) && empty($this->request->template)) {
            return $this->returnApi(201, '模版不能为空');
        }
        // if (in_array($this->request->location, [1, 2, 3, 4, 5]) && !empty($this->request->resource_business_type_id) && $this->request->resource_business_type_id != $this->request->location) {
        //     return $this->returnApi(201, '显示位置与资源商的类型需要对应');
        // }
        $is_exists = $this->model->nameIsExists($this->request->type_name, 'type_name', $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, "该名称已存在");
        }

        $system_type_info = $this->model->detail($this->request->id);
        if (empty($system_type_info)) {
            return $this->returnApi(202, "该类型不存在");
        }
        if ($system_type_info['template'] != $this->request->template) {
            if (in_array($system_type_info['location'], [1, 2, 3, 4, 5])) {
                $big_type_id_all[] = $system_type_info['location']; //固定是这些数据了
            } else {
                if ($system_type_info['way'] == 3) {
                    $resourceTotalModel = new ResourceTotal();
                    $big_type_id_all = $resourceTotalModel->getBigTypeIdByResourceId($this->request->resource_business_id, $this->request->resource_business_type_id);
                } elseif (in_array($system_type_info['way'], [1, 5])) {
                    $resourceSystemTypeIntentionModel = new ResourceSystemTypeIntention();
                    $big_type_id_all = $resourceSystemTypeIntentionModel->getBigTypeIdBySystemTypeId($this->request->resource_business_type_id);
                }
            }
            if ($system_type_info['way'] == 5 && in_array(3, $big_type_id_all)) {
                return $this->returnApi(202, "该类型下的资源存在视频，不能选择此书籍获取方式");
            }
            if (in_array($this->request->template, [1, 2, 3, 4, 5, 6, 7]) && in_array(3, $big_type_id_all)) {
                return $this->returnApi(202, "该类型下的资源存在视频，不能选择此模版");
            }
            if (in_array($this->request->template, [8]) && (count($big_type_id_all) > 1 || $big_type_id_all != 3)) {
                return $this->returnApi(202, '该类型下存在非视频资源，不能选择此模版');
            }
        }

        if (in_array($this->request->way, [2, 4, 5])) {
            $this->request->merge(['template' => '']);
        }
        if (empty($this->request->sort)) {
            $this->request->merge(['sort' => 0]);
        }
        $data = $this->request->all();
        unset($data['way']); //暂不支持修改方式
        $res = $this->model->change($data);

        if (!$res) {
            return $this->returnApi(202, "修改失败");
        }
        return $this->returnApi(200, "修改成功", true);
    }

    /**
     * 删除
     * @param id int 类型id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 撤销 和 发布
     * @param ids int 书单id  多个逗号拼接  all全部
     * @param is_play int 发布   1 发布  2 撤销
     */
    public function cancelAndRelease()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_and_release')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        DB::beginTransaction();
        try {
            list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

            $is_play = $this->request->is_play == 1 ? '发布' : '撤销';

            DB::commit();
            return $this->returnApi($code, $is_play . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最小
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
